package com.oocl.tm.service.impl;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Date;

import com.oocl.tm.log4j.Log4j;
import com.oocl.tm.protocol.MsgPackage;
import com.oocl.tm.protocol.Operation;
import com.oocl.tm.repository.ClientsDBFactory;
import com.oocl.tm.service.ChatService;
import com.oocl.tm.util.JsonUtil;

public class ChatServiceImpl implements ChatService{
	
	private OutputStream out;
	private MsgPackage msgPackage;
	
	public ChatServiceImpl(MsgPackage msgPackage) {
		this.msgPackage = msgPackage;
	}

	@Override
	public void transmitMsgPt() throws IOException {
		msgPackage.setOnlineMap(ClientsDBFactory.getClientsList());   //实时更新在线人数
		Log4j.getLogger().info("[ the msgPackage info before transmit: ] "+msgPackage.toString());
		
		if(msgPackage.getReceiver().equals("ALL")){
			msgPackage.setOnlineMap(ClientsDBFactory.getClientsList());   //实时更新在线人数
			for(String receiver:ClientsDBFactory.getClientsList().keySet()){   //只发给在线clients
				if(ClientsDBFactory.getClientsList().get(receiver)){
//					out.write(JsonUtil.parserToString(msgPackage).getBytes());
					out = ClientsDBFactory.getOutputsList().get(receiver);
					out.write(JsonUtil.parserToString(msgPackage).getBytes());
				}
			}
		}else {  
			try{//当所发给用户不在线
				if(ClientsDBFactory.getClientsList().get(msgPackage.getReceiver())){  //所发给用户是否在线
					out = ClientsDBFactory.getOutputsList().get(msgPackage.getReceiver());
					out.write(JsonUtil.parserToString(msgPackage).getBytes());
				}
			}catch(Exception e){
				
			}
		}
			
	}

}
